<!-- equipmentLedger -->
<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag" :class="isCloseTree ? 'tag-nav-close' : ''">
        <div class="main-nav">
          <div class="search-box">
            <a-button class="btns-item" size="small" @click="expandAll(true)">
              <Icon icon="ant-design:merge-cells-outlined" />
            </a-button>
            <a-button class="btns-item" size="small" @click="expandAll(false)">
              <Icon icon="ant-design:split-cells-outlined" />
            </a-button>
            <a-input-search
              v-model:value="searchDriver"
              placeholder="搜索"
              :allowClear="true"
              @search="onSearchDriver"
            />
          </div>
          <BasicTree
            title=""
            ref="treeRef"
            :treeData="treeDataPro"
            :fieldNames="{ key: 'Key', title: 'Name', children: 'Children' }"
            :onSelect="handleTreeSelect"
          />
        </div>
        <div class="main-sidebar" @click="handleSideBarClick">
          <div class="close-btn">
            <Icon
              :icon="
                isCloseTree ? 'ant-design:caret-right-filled' : 'ant-design:caret-left-outlined'
              "
            />
          </div>
        </div>
        <div class="main-content">
          <div class="form-box" v-show="enterpriseInfo.Key">
            <BasicForm @register="registerForm" />
            <div class="btns-box">
              <a-button class="btns-one" @click="throttleReset">重置</a-button>
              <a-button type="primary" @click="throttleSubmit">查询</a-button>
            </div>
          </div>
          <div class="card-list">
            <div
              class="card-list-item"
              v-for="(item, index) in cardList"
              :key="index"
              @click="handleJumpPage(item)"
            >
              <div class="item-head">
                <div class="item-head-tags">
                  <!-- 链接状态 -->
                  <a-tag
                    :color="
                      (ConnectStateConfig[item.ConnectState] || ConnectStateConfig.default).color
                    "
                    >{{
                      (ConnectStateConfig[item.ConnectState] || ConnectStateConfig.default).txt
                    }}</a-tag
                  >
                  <!-- 运行状态 -->
                  <a-tag :color="(RunStateConfig[item.RunState] || RunStateConfig.default).color">{{
                    (RunStateConfig[item.RunState] || RunStateConfig.default).txt
                  }}</a-tag>
                  <!-- 是否报警 -->
                  <a-tag :color="AlarmStateConfig[item.AlarmState].color">{{
                    item.AlarmState === 0 ? AlarmStateConfig[item.AlarmState].txt : item.AlarmLevel
                  }}</a-tag>
                </div>
                <Icon
                  icon="ant-design:star-filled"
                  class="star-box"
                  :class="item.CollectSign ? 'star-box-collect' : ''"
                  @click="handleCollect(item)"
                />
              </div>
              <div class="item-nav">
                <div class="item-nav-img">
                  <img :src="item.img" />
                </div>
                <div class="item-nav-info">
                  <div class="info-con">
                    设备编码：<span>{{ item.Code }}</span>
                  </div>
                  <div class="info-con">
                    设备名称：<span>{{ item.Name }}</span>
                  </div>
                  <div class="info-con">
                    设备型号：<span>{{ item.ModelCode }}</span>
                  </div>
                </div>
              </div>
              <div
                class="description-box"
                :style="{
                  'background-color': (RunStateConfig[item.RunState] || RunStateConfig.default)
                    .backgroundColor,
                }"
                ref="scrollListRefs"
              >
                <template v-if="!item.Tags || item.Tags.length === 0">
                  <div class="description-box-null">请同步物联参数</div>
                </template>
                <template v-else>
                  <a-descriptions size="small" :column="2">
                    <a-descriptions-item
                      v-for="(v, i) in item.Tags"
                      :key="i"
                      :label="v.Name"
                      :label-style="{
                        color: item.RunState === 0 ? '#999' : '#606266',
                        minWidth: '65px',
                        'font-size': '13px',
                        'line-height': 1.4,
                      }"
                      :contentStyle="{ 'font-size': '12px', 'line-height': 1.1 }"
                    >
                      {{ v.Value }}
                    </a-descriptions-item>
                  </a-descriptions>
                </template>
              </div>
            </div>
          </div>
          <div class="load-more">
            <a-button v-if="cardList.length > 0" :disabled="!isNextPage" @click="handleNextPage">{{
              isNextPage ? '加 载 更 多' : '已经到底了'
            }}</a-button>
          </div>
        </div>
      </div>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '/@/components/Page';
  import { ref, onMounted, unref, nextTick, computed, onBeforeUnmount } from 'vue';
  import { Tag } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { BasicTree, TreeActionType } from '/@/components/Tree/index';
  import { useDebounceFn } from '@vueuse/core';
  import { Descriptions, DescriptionsItem } from 'ant-design-vue';
  import { getenterprisetree } from '/@/api/enterprise/index';
  import { getequipmentcard } from '/@/api/equipmentLedger/index';
  import { getdevicetypes } from '/@/api/equipmentType/index';
  import { getdevicemodels } from '/@/api/equipmentModel/index';
  import { getUrlProfix } from '/@/utils/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useRouter } from 'vue-router';
  // import { autoScroll } from '/@/views/project/alertRules/components/vScaleScreen';
  // 跳转
  const router = useRouter();
  let ATag = Tag;
  const ADescriptionsItem = DescriptionsItem;
  const ADescriptions = Descriptions;
  let searchDriver = ref('');
  let treeDataPro = ref([]);
  let loading = ref(false);
  const { createMessage } = useMessage();
  const { t } = useI18n();
  let isCloseTree = ref(false);
  // let treeClickCount = 0;
  let cardList = ref([]);
  // 是否可以继续加载下一页
  const isNextPage = computed(
    () =>
      paginationInfo.value.current > paginationInfo.value.totalPage &&
      paginationInfo.value.totalPage > 0,
  );
  // 分页信息
  let paginationInfo = ref({
    pageSize: 50,
    total: 0,
    totalPage: 0,
    current: 1,
  });
  let RunStateConfig = {
    0: {
      color: '#d7d7d7',
      txt: '关机',
      backgroundColor: 'rgb(215, 215, 215)',
    },
    1: {
      color: '#339966',
      txt: '运行',
      backgroundColor: '#f6ffed',
    },
    2: {
      color: '#d9f79d',
      txt: '待机',
      backgroundColor: 'rgba(255, 255, 153,0.6)',
    },
    3: {
      color: '#6bbff0',
      txt: '停机',
      backgroundColor: 'rgba(107, 191, 240,0.2)',
    },
    4: {
      color: '#edb263',
      txt: '暂停',
      backgroundColor: 'rgba(237, 178, 99,0.2)',
    },
    5: {
      color: '#89d6b0',
      txt: '调机',
      backgroundColor: 'rgba(137, 214, 176,0.2)',
    },
    6: {
      color: '#CC3333',
      txt: '故障',
      backgroundColor: '#fff1f0',
    },
    default: {
      color: '#d7d7d7',
      txt: '未知',
      backgroundColor: 'rgb(215, 215, 215)',
    },
  };
  let ConnectStateConfig = {
    0: {
      color: '#d7d7d7',
      txt: '离线',
    },
    1: {
      color: 'green',
      txt: '在线',
    },
    2: {
      color: 'red',
      txt: '离线',
    },
    3: {
      color: '#d7d7d7',
      txt: '未联机',
    },
    default: {
      color: '#d7d7d7',
      txt: '未知',
    },
  };
  let AlarmStateConfig = {
    0: {
      color: '#d7d7d7',
      txt: '报警',
    },
    1: {
      color: 'red',
      txt: '',
    },
    2: {
      color: 'red',
      txt: '',
    },
  };
  const throttleSubmit = useDebounceFn(handleSubmit, 500);
  const throttleReset = useDebounceFn(handleResetFields, 500);
  const treeRef = ref<Nullable<TreeActionType>>(null);

  //参数列表滚动
  let scrollListRefs = ref<HTMLElement[]>([]);
  let scrollIntervals = ref<number[]>([]); // 用于存储计时器 ID

  // 企业信息
  let enterpriseInfo = {};
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'SearchCategory',
      component: 'Select',
      label: '设备类别：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [
          { label: '全部', value: 0 },
          { label: '生产设备', value: 1 },
          { label: '检测设备', value: 2 },
          { label: '辅助设备', value: 3 },
          { label: '厂务设备', value: 4 },
          { label: '仪器仪表', value: 5 },
          { label: '办公设备', value: 6 },
          { label: 'IT设备', value: 7 },
          { label: '其它', value: 8 },
        ],
      },
    },
    {
      field: 'searchTypeName',
      component: 'Select',
      label: '设备类型：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'TypeName', value: 'Id', key: 'Id' },
      },
    },
    {
      field: 'SearchModelCode',
      component: 'Select',
      label: '设备型号：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'ModelName', value: 'ModelCode', key: 'ModelCode' },
      },
    },
    {
      field: 'SearchCode',
      component: 'Input',
      label: '设备编码：',
      colProps: {
        span: 6,
      },
    },
  ];
  const [registerForm, { validateFields, setFieldsValue, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  function handleJumpPage(item) {
    console.log(item);
    router.push({
      name: 'EqIntegrationDetailPage',
      query: { FullName: item.FullName, ConnectState: item.ConnectState },
    });
  }
  // 加载下一页
  async function handleNextPage() {
    paginationInfo.value.current = paginationInfo.value.current + 1;
    let res = await validateFields();
    getCardData(res, true);
  }
  // 收藏操作
  async function handleCollect(item) {
    try {
      loading.value = true;
      await getequipmentcard([
        {
          SearchCode: '',
          SearchModelCode: '',
          searchTypeName: '',
          SearchCategory: 0,
          SearchEnterpriseId: enterpriseInfo.Key,
          PageNO: 1,
          PageSize: 1,
          EquipmentCardInfo: {
            Id: item.Id,
            CollectSign: !item.CollectSign,
          },
        },
      ]);
      cardList.value.forEach((element) => {
        if (element.Id === item.Id) {
          element.CollectSign = !item.CollectSign;
        }
      });
      createMessage.success(t('layout.setting.operatingTitle'));
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 获取设备类型
  async function getDeviceTypes() {
    try {
      loading.value = true;

      let res = await getdevicetypes([
        {
          PageNO: 1,
          SearchTypeName: '',
          SearchCategory: 0,
          PageSize: 1000,
        },
      ]);
      updateSchema({
        field: 'searchTypeName',
        componentProps: {
          options: res.Rows,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 获取设备型号
  async function getDeviceModels() {
    try {
      loading.value = true;

      let res = await getdevicemodels([
        {
          PageNO: 1,
          searchModel: '',
          searchModelName: '',
          searchTypeName: '',
          searchTypeCategory: 0,
          PageSize: 1000,
        },
      ]);
      updateSchema({
        field: 'SearchModelCode',
        componentProps: {
          options: res.Rows,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 重置搜索条件
  function initSearch() {
    setFieldsValue({
      SearchTypeName: '',
      SearchCode: '',
      SearchModelCode: undefined,
      SearchCategory: 0,
    });
    paginationInfo.value.current = 1;
  }
  // 重置按钮点击事件
  async function handleResetFields() {
    initSearch();
  }
  // 获取设备设备卡片
  async function getCardData(params = {}, isPush = false) {
    try {
      loading.value = true;
      scrollIntervals.value.forEach((intervalId) => {
        clearInterval(intervalId); // 清除每个计时器
      });
      let res = await getequipmentcard([
        {
          SearchCode: '',
          SearchModelCode: '',
          searchTypeName: '',
          SearchCategory: 0,
          SearchEnterpriseId: enterpriseInfo.Key,
          PageNO: paginationInfo.value.current,
          PageSize: paginationInfo.value.pageSize,
          ...params,
        },
      ]);
      paginationInfo.value.total = res.TotalRows;
      paginationInfo.value.totalPage = res.TotalPage;
      let imgUrl = getUrlProfix();
      let list = res.Rows.map((item) => {
        item.img = imgUrl + item.Img;
        return item;
      });
      if (isPush) {
        cardList.value = [...cardList.value, ...list];
      } else {
        cardList.value = list;
      }
      console.log(cardList.value);
      loading.value = false;

      // 滚动事件
      nextTick(() => {
        scrollListRefs.value.forEach((scrollElement, index) => {
          if (scrollElement) {
            let scrollAmount = 0;
            const scrollStep = 1; // 每次滚动的像素数
            const scrollInterval = 50; // 滚动间隔时间，单位毫秒

            const intervalId = setInterval(() => {
              scrollAmount += scrollStep;
              if (scrollAmount >= scrollElement.scrollHeight - scrollElement.clientHeight) {
                scrollAmount = 0; // 重置滚动
              }
              scrollElement.scrollTop = scrollAmount;
            }, scrollInterval);

            scrollIntervals.value[index] = Number(intervalId); // 保存计时器 ID
          }
        });
      });
    } catch (error) {
      loading.value = false;
    }
  }
  // 查询按钮点击事件
  async function handleSubmit() {
    let res = await validateFields();
    getCardData(res);
  }
  // 折叠左侧区域
  function handleSideBarClick() {
    isCloseTree.value = !isCloseTree.value;
  }
  // 展开 折叠
  function expandAll(checkAll) {
    getTree().expandAll(checkAll);
  }
  // 获取树数据
  async function initData(isOpenTree = false) {
    loading.value = true;
    let resByTree = await getenterprisetree(
      searchDriver.value ? [true, searchDriver.value] : [true, null],
    );
    treeDataPro.value = resByTree || [];
    if (isOpenTree) {
      nextTick(() => {
        getTree().filterByLevel(1);
      });
    }

    loading.value = false;
  }
  // 获取树dom
  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  // 树点击事件
  function handleTreeSelect(_e, info) {
    let val = info.node || {};
    enterpriseInfo = val;
    initSearch();
    getCardData();
    // treeClickCount++;

    // //单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
    // if (treeClickCount >= 2) {
    //   return;
    // }
    // //计时器,计算300毫秒为单位,可自行修改
    // setTimeout(() => {
    //   if (treeClickCount == 1) {
    //     //把次数归零
    //     treeClickCount = 0;
    //     // 单击事件
    //     // handleClickByTree(info);
    //   } else if (treeClickCount > 1) {
    //     //把次数归零
    //     treeClickCount = 0;
    //     //双击事件
    //     handleDbClickByTree(info);
    //   }
    // }, 300);
  }
  // // 双击事件
  // function handleDbClickByTree(info) {
  //   let val = info.node || {};
  //   console.log(`output->val`, val);
  // }
  // 搜索树
  function onSearchDriver() {
    initData();
  }
  // 在组件挂载时初始化滚动
  onMounted(() => {
    initData(true);
    getDeviceTypes();
    getDeviceModels();
    nextTick(() => {
      scrollListRefs.value.forEach((scrollElement, index) => {
        if (scrollElement) {
          let scrollAmount = 0;
          const scrollStep = 1; // 每次滚动的像素数
          const scrollInterval = 50; // 滚动间隔时间，单位毫秒

          const intervalId = setInterval(() => {
            scrollAmount += scrollStep;
            if (scrollAmount >= scrollElement.scrollHeight - scrollElement.clientHeight) {
              scrollAmount = 0; // 重置滚动
            }
            scrollElement.scrollTop = scrollAmount;
          }, scrollInterval);

          scrollIntervals.value[index] = intervalId as unknown as number; // 保存计时器 ID
        }
      });
    });
  });
  // 页面销毁之前，清除滚动
  onBeforeUnmount(() => {
    scrollIntervals.value.forEach((intervalId) => {
      clearInterval(intervalId); // 清除每个计时器
    });
  });
</script>
<script lang="ts">
  export default {
    name: 'EquipmentCardIndexPage',
  };
</script>
<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .search-box {
        display: flex;
        align-items: center;

        > .ant-btn-sm {
          height: 32px;
        }
      }

      .main-nav {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        width: 240px;
        height: calc(100%);
        padding: 8px;
        box-sizing: border-box;
        overflow: auto;
        border-right: 1px solid #ccc;

        ::v-deep(.vben-tree__title) {
          user-select: none !important;
        }
      }

      .main-sidebar {
        position: absolute;
        top: 0;
        left: 240px;
        bottom: 0;
        width: 12px;
        border-radius: 5px;
        cursor: pointer;
        user-select: none;

        .close-btn {
          position: absolute;
          top: 50%;
          left: 0;
          width: 12px;
          height: 30px;
          margin-top: -50%;

          line-height: 30px;
          text-align: center;
          background: #7dcdfe;
          border-radius: 6px;
          color: #fff;

          > span {
            font-size: 12px !important;
          }
        }
      }

      .main-sidebar:hover {
        background-color: #e2e3e5;
      }

      .main-content {
        position: relative;
        height: 100%;
        margin-left: 260px;
        overflow: hidden;
      }

      .main-content::after {
        content: '';
        display: block;
        width: 100%;
        height: 45px;
      }
    }

    .tag-nav-close {
      .main-nav {
        left: -260px;
      }

      .main-sidebar {
        left: 0;
      }

      .main-content {
        margin-left: 20px;
      }
    }
  }

  .form-box {
    padding: 5px;

    ::v-deep(.ant-form-item) {
      margin: 0 5px;
      margin-bottom: 8px;
    }
  }

  .btns-box {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 5px;

    .btns-one {
      margin-right: 10px;
    }
  }

  .card-list {
    width: 100%;
    display: flex;
    flex-wrap: wrap;

    .card-list-item {
      cursor: pointer;
      // min-width: 20.9rem;
      // max-width: 25%;
      width: 24%;
      margin: 5px;
      padding: 5px;
      box-sizing: border-box;
      box-shadow: 0.1px 0px 5.3px rgba(0, 0, 0, 0.012), 0.4px 0px 17.9px rgba(0, 0, 0, 0.018),
        2px 0px 80px rgba(0, 0, 0, 0.03);
      border-radius: 5px;

      .item-head {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        ::v-deep(.ant-tag) {
          border-radius: 15px;
        }

        .star-box {
          cursor: pointer;
          color: #d7d7d7;
          font-size: 26px !important;
        }

        .star-box-collect {
          color: #f3cd97;
        }
      }

      .item-nav {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 5px 0;

        .item-nav-img {
          height: 72px;
          width: 90px;
          border-radius: 5px;
          overflow: hidden;

          > img {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }

        .item-nav-info {
          flex: 1;
          padding-left: 20px;
          box-sizing: border-box;

          .info-con {
            color: #999;

            > span {
              color: #000;
              font-weight: 700;
            }
          }
        }
      }

      .description-box {
        width: 100%;
        height: 120px !important;
        overflow: hidden;
        background-color: #e0e9ed;
        box-sizing: border-box;
        padding: 5px;
        border-radius: 5px;
        min-height: 120px;

        .description-box-null {
          width: 100%;
          text-align: center;
          height: 100px;
          line-height: 100px;
          font-weight: 600;
          color: #9999995e;
          font-size: 20px;
        }
      }
    }
  }

  .load-more {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
